from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union

from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.db.session import Base

ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)


class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
    """
    基础CRUD操作类
    """
    def __init__(self, model: Type[ModelType]):
        self.model = model

    def get(self, db: Session, id: Any) -> Optional[ModelType]:
        """
        根据ID获取记录
        """
        return db.query(self.model).filter(self.model.id == id).first()

    def get_multi(
        self, db: Session, *, skip: int = 0, limit: int = 100
    ) -> List[ModelType]:
        """
        获取多条记录
        """
        return db.query(self.model).offset(skip).limit(limit).all()

    def create(self, db: Session, *, obj_in: CreateSchemaType, created_by: str = None) -> ModelType:
        """
        创建记录
        """
        obj_in_data = jsonable_encoder(obj_in)
        db_obj = self.model(**obj_in_data)
        if created_by:
            db_obj.create_by = created_by
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def update(
        self,
        db: Session,
        *,
        db_obj: ModelType,
        obj_in: Union[UpdateSchemaType, Dict[str, Any]],
        updated_by: str = None
    ) -> ModelType:
        """
        更新记录，包含版本控制
        """
        obj_data = jsonable_encoder(db_obj)
        
        # 版本控制检查
        if hasattr(obj_in, "version"):
            input_version = obj_in.version
            if input_version != db_obj.version:
                raise ValueError("数据已被修改，请刷新后再试")
            # 递增版本号
            db_obj.version += 1
        
        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)
        
        # 排除版本字段
        if "version" in update_data:
            update_data.pop("version")
            
        for field in obj_data:
            if field in update_data:
                setattr(db_obj, field, update_data[field])
        
        if updated_by:
            db_obj.update_by = updated_by
        
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def remove(self, db: Session, *, id: int) -> ModelType:
        """
        删除记录 (实际操作为物理删除，子类可重写实现逻辑删除)
        """
        obj = db.query(self.model).get(id)
        db.delete(obj)
        db.commit()
        return obj